package com.masterclient.app;

/**
 * Created by gyq on 2017/2/16.
 */

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;

/**
 *
 * Title: FileUtils.java
 * Description: 对sd卡的文件相关操作
 * @author Liusong
 * @date 2015-1-12
 * @version V1.0
 */
public class FileUtils {

    /**
     * 判断sdcrad是否已经安装
     * @return boolean true安装 false 未安装
     */
    public static boolean isSDCardMounted(){
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 得到sdcard的路径
     * @return
     */
    public static String getSDCardRoot(){
        if(isSDCardMounted()){
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return "";
    }

    /**
     * 获取cache路径
     *
     * @param context
     * @return
     */
    public static String getPreloadsFileCache(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir().getPath();
        } else {
            return context.getCacheDir().getPath();
        }
    }
    /**
     * 创建文件的路径
     * @param path 路径，方法中以默认包含了sdcard的路径，path格式是"/path...."
     * @return 返回文件的路径，创建失败的话返回为空
     */
    public static String createMkdirs(String path) {
        if (TextUtils.isEmpty(path)) {
//            throw new RuntimeException("路径为空");
            return null;
        }
        path = getSDCardRoot()+path;
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.mkdirs();
            } catch (Exception e) {
//                throw new RuntimeException("创建文件夹不成功");
                e.printStackTrace();
                return null;
            }
        }
        return file.getAbsolutePath();
    }

    /**
     * 创建文件的路径及文件
     * @param path 路径，方法中以默认包含了sdcard的路径，path格式是"/path...."
     * @param filename 文件的名称
     * @return 返回文件的路径，创建失败的话返回为空
     */
    public static String createMkdirsAndFiles(String path, String filename) {
        if (TextUtils.isEmpty(path)) {
//            throw new RuntimeException("路径为空");
            return null;
        }
        path = getSDCardRoot()+path;
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.mkdirs();
            } catch (Exception e) {
//                throw new RuntimeException("创建文件夹不成功");

                e.printStackTrace();
                return null;
            }
        }
        File f = new File(file, filename);
        if(!f.exists()){
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return f.getAbsolutePath();
    }

    /**
     * 把内容写入文件
     * @param path 文件路径
     * @param text 内容
     */
    public static void write2File(String path,String text,boolean append){
        BufferedWriter bw = null;
        try {
            //1.创建流对象
            bw = new BufferedWriter(new FileWriter(path,append));
            //2.写入文件
            bw.write(text);
            //换行刷新
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //4.关闭流资源
            if(bw!= null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static File fileInvailed(String path) {
        if (TextUtils.isEmpty(path)) {
//            throw new RuntimeException("路径为空");
            return null;
        }
        File file = new File(path);
        if (!file.exists()) {
            try {
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return file;
    }

    /**
     * 检查文件是否存在
     */
    public static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    /**
     * 获取指定文件大小 　　
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {

            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 转换文件大小
     */
    public static String toFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 判断视频文件是否大于20MB
     * @param size
     * @return
     */
    public static boolean checkVideoSize(long size){
        if (size > 1048576){
            double videoSize =size / 1048576;
            if (videoSize > 20){
                return false;
            }
        }



        return true;
    }

    /**
     * 判断t图片文件是否大于15MB
     * @param size
     * @return
     */
    public static boolean checkImageSize(long size){
        if (size > 1048576){
            double videoSize =size / 1048576;
            if (videoSize > 15){
                return false;
            }
        }

        return true;
    }

    public static String getCachePath(Context context, String dir) {
        boolean sdCardExist = false;

        try {
            sdCardExist = "mounted".equals(Environment.getExternalStorageState());
        } catch (Exception var8) {
            Log.e("crashLog", "getCachePath", var8);
        }

        File cacheDir;
        if (Build.VERSION.SDK_INT < 19 && !hasFilePermission(context)) {
            cacheDir = new File(FileUtils.getSDCardRoot()+ "/gzg");
        } else {
            try {
//                cacheDir = context.getExternalCacheDir();
                cacheDir = new File(FileUtils.getSDCardRoot()+  "/gzg");
            } catch (ArrayIndexOutOfBoundsException var7) {
                Log.e("crashLog", "getCachePath ArrayIndexOutOfBoundsException", var7);
                cacheDir = null;
            }
        }

        if (!sdCardExist || cacheDir == null || !cacheDir.exists() && !cacheDir.mkdirs()) {
            cacheDir = new File(FileUtils.getSDCardRoot()+  "/gzg");
        }

        File tarDir = new File(cacheDir.getPath() + File.separator + dir);
        boolean result;
        if (tarDir.exists() && tarDir.isFile()) {
            result = tarDir.delete();
            Log.e("crashLog", "getCachePath isDelete:" + result);
        }

        if (!tarDir.exists()) {
            result = tarDir.mkdir();
            Log.w("crashLog", "getCachePath = " + tarDir.getPath() + ", result = " + result);
            if (!result) {
                if (Build.VERSION.SDK_INT >= 23 && hasFilePermission(context)) {
                    tarDir = new File("/sdcard/cache/" + dir);
                    if (!tarDir.exists()) {
                        result = tarDir.mkdirs();
                    }
                } else {
                    File filesDir = context.getFilesDir();
                    tarDir = new File(filesDir, dir);
                    if (!tarDir.exists()) {
                        result = tarDir.mkdirs();
                    }
                }

                Log.e("crashLog", "change path = " + tarDir.getPath() + ", result = " + result);
            }
        }

        return tarDir.getPath();
    }

    private static boolean hasFilePermission(Context context) {
        return context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") == 0;
    }


    public static void saveTxt(String message,String filePath,String name){
        String fileName = name+".txt";
        writeTxtToFile(message, filePath, fileName);
    }


    // 将字符串写入到文本文件中
    private static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + "/" + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

//生成文件

    private static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

//生成文件夹

    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

}
